package com.ssy.invoicing.web.velocity.tool;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.tools.view.context.ViewContext;
import org.apache.velocity.tools.view.tools.ContextTool;

public class VelocityTool extends ContextTool {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected ServletContext context;
    protected VelocityContext velocity;
    
    @Override
    public void init(Object arg0) {
        //scope: request or session
        if(arg0 instanceof ViewContext){
            ViewContext viewContext = (ViewContext) arg0;
            request = viewContext.getRequest();
            response = viewContext.getResponse();
            context = viewContext.getServletContext();
            velocity = (VelocityContext)viewContext.getVelocityContext();
        }
        //scope: application
        else if(arg0 instanceof ServletContext){
            context = (ServletContext)arg0;
        }
    }

    /**
     * 获取web应用的上下文路径
     * 
     * @return
     */
    public String root() {
        return request.getContextPath();
    }
}
